# 功能模块：前端业务代码入口
# 作者：dl
# 描述：仅做简单的操作UI，所有的数据UI均放在GMQM系统

from trame.ui.vuetify import VAppLayout
from trame.widgets import vtk as vtkTrame, vuetify, trame, html,iframe,client
from trame.app import get_server

from pathlib import Path

parent_css_dir = Path(__file__).parent / "css"
css_dir = parent_css_dir / "css"

CSS_FILE = css_dir.with_name("gloabl.css")


class lusterUI:
    # 构造函数,注意，切勿在子组件中自行使用在这里未定义的字段，否则会造成页面刷新一次
    def __init__(self):
        self.server = get_server()
        self.server.client_type = "vue2"
        self.ctrl = self.server.controller

        self.visualization = None  # 引擎

        # 状态机，目前只知道有一个状态机，为了方便维护，所有的双向绑定字段均维护在这里
        self.state = self.server.state

        self.state.rightMenuStyle = {"display": "none"}  # 右键菜单栏的样式
        self.state.devicePixelRatio = 1  # 客户端像素比

        self.state.renderViewStyle = None
        self.state.renderSpiltViewStyle = None

    def hideActor(self):
        self.visualization.mouseInteractorEvent.hideActor()

    def showAllActor(self):
        self.visualization.mouseInteractorEvent.showAllActor()

    # 事件分发接口，根据不同参数调用不同的方法
    def receiveParentMsg(self,param):
        # 工厂场景
        if param["eventScene"] == "factory":
            # 前往车间
            if param["eventName"] =="factory_go_workshop":
                self.visualization.factory.leaveScene()
                self.visualization.workshop.enterScene()
            # 切换背景
            if param["eventName"] =="factory_change_background":
                self.visualization.factory.changeEvn(param["bgIndex"])
            # 漫游视角
            elif param["eventName"] =="factory_roam_view":
                self.visualization.factory.roamView()
        # 车间场景
        elif param["eventScene"] == "workshop":
            # 前往产线
            if param["eventName"] =="workshop_go_productline":
                self.visualization.workshop.leaveScene()
                self.visualization.productline.enterScene(False)
                self.ctrl.view_update()
            # 前往工厂
            if param["eventName"] =="workshop_go_factory":
                self.visualization.workshop.leaveScene()
                self.visualization.factory.enterScene()
                self.ctrl.view_update()
            # 切换背景
            elif param["eventName"] =="workshop_change_background":
                self.visualization.workshop.changeEvn(param["bgIndex"])
        # 产线场景
        elif param["eventScene"] == "productline":
            # 产线停机/复机
            if param["eventName"] =="productline_opt_device":
                if param["switch"] == "on":
                    self.visualization.productline.animationFlag = True
                    # self.visualization.productline.async_animation()
                else:
                    self.visualization.productline.animationFlag = False
            # 切换配方
            elif param["eventName"] =="productline_switch_recipes":
                print("切换配方")
                self.ctrl.sendMsgToParent(111)

            # 显示/隐藏健康度
            elif param["eventName"] =="productline_opt_healthDegree":
                if param["switch"] == "on":
                    self.visualization.productline.showHealthDegree()
                else:
                    self.visualization.productline.resetHealthDegree()
            # 前往车间
            elif param["eventName"] =="productline_go_workshop":
                self.visualization.productline.leaveScene()
                self.visualization.workshop.enterScene()
            # 前往设备
            elif param["eventName"] =="productline_go_device":
                self.visualization.productline.leaveScene()
                self.visualization.device.enterScene()
            # 重置视角
            elif param["eventName"] =="productline_rest_camera":
                self.visualization.productline.restCamera()
                self.visualization.productline.splitRenderWindow.restCamera()
                self.ctrl.view_update() # 必须更新两次，否则3d页面不会刷新
                self.ctrl.view_update() # 必须更新两次，否则3d页面不会刷新
            # 如果3d视窗不能设置为透明则此处需要修改
            elif param["eventName"] =="productline_change_background":
                self.visualization.productline.changeEvn(param["bgIndex"])
                self.visualization.productline.splitRenderWindow.changeEvn(param["bgIndex"])
            elif param["eventName"] =="productline_switch_animation":
                self.visualization.productline.command(param["animation_index"])
        # 设备场景
        elif param["eventScene"] == "device":
            # 前往产线
            if param["eventName"] =="device_go_productline":
                self.visualization.device.leaveScene()
                self.visualization.productline.enterScene(False)
                self.ctrl.view_update()
            if param["eventName"] =="device_go_product":
                self.visualization.device.leaveScene()
                self.visualization.product.enterScene_mesh()
                self.ctrl.view_update()
            # 设备停机/复机
            if param["eventName"] =="device_opt_device":
                if param["switch"] == "on":
                    self.visualization.device.animationFlag = True
                    self.visualization.device.async_animation()
                else:
                    self.visualization.device.animationFlag = False
            # 切换配方
            elif param["eventName"] =="productline_switch_recipes":
                print("切换配方")
            # 切换背景
            elif param["eventName"] =="device_change_background":
                self.visualization.device.changeEvn(param["bgIndex"])
            # 选择产品进入产品场景
            elif param["eventName"] =="device_select_product":
                self.visualization.device.leaveScene()
                self.visualization.product.enterScene(param["productItem"])
                self.ctrl.view_update()
        # 产品场景
        elif param["eventScene"] == "product":
            # 前往产线
            if param["eventName"] =="product_go_device":
                self.visualization.product.leaveScene()
                self.visualization.device.enterScene()
                self.ctrl.view_update()
            # 切换背景
            elif param["eventName"] =="product_change_background":
                self.visualization.product.changeEvn(param["bgIndex"])
            # 切换显示方式
            elif param["eventName"] =="product_change_showtype":
                self.visualization.product.changeShowType(param["showType"])
            elif param["eventName"] =="product_select_defect":
                self.visualization.product.selectDefect(param["id"])
        # 预处理
        else:
            print("未识别到到eventScene：",param["eventScene"])

    # 绘制UI
    def drawUI(self, visualization):
        self.visualization = visualization
        with VAppLayout(self.server) as layout:
            trame.ClientTriggers(
            created="""
                devicePixelRatio = window.devicePixelRatio;
                window.document.oncontextmenu = () => false;
            """
            )

            comm = iframe.Communicator(
                event_names=["parent_to_child"],
                parent_to_child=(self.receiveParentMsg, "[$event]"),
            )

            # 定义像父页面发现信息的机制
            sendMsgToParent = client.JSEval(
                exec="window.parent.postMessage($event, '*');"
            )
            # 这个语法必须这么写，否则会出莫名其妙的错误
            self.ctrl.sendMsgToParent = sendMsgToParent.exec

            with vuetify.VContainer(
                fluid=True,
                classes="pa-0 fill-height",
                style="position: relative;background-color: transparent;"
            ):
                with html.Div(
                    style=("renderViewStyle",)
                ):
                    view = vtkTrame.VtkRemoteView(
                        visualization.renderWindow,
                        ref="view"
                    )

                    self.ctrl.view_update = view.update

                with html.Div(
                    style=("renderSpiltViewStyle",)
                ):
                    view_split = vtkTrame.VtkRemoteView(
                        visualization.productline.splitRenderWindow.renWin,
                        ref="view1",
                        interactive_ratio=1,
                        interactive_quality=120,
                        classes="share-canvas",
                    )
                    self.ctrl.view_split_update = view_split.update


                # 右键菜单栏
                with vuetify.VBtnToggle(
                    style=("rightMenuStyle", {"vertical": "True"}), dense=True, vertical=True
                ):
                    with vuetify.VBtn(
                        icon=True, click=self.hideActor
                    ):
                        vuetify.VIcon("mdi-eye-off")
                    with vuetify.VBtn(
                        icon=True, click=self.showAllActor
                    ):
                        vuetify.VIcon("mdi-eye-refresh")

            client.Style(CSS_FILE.read_text())
        
